package com.wxmit.ot.handler;

import com.wxmit.ot.base.ApiResult;
import com.wxmit.ot.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author huangxiong
 * @version V1.0
 * @date 2023/2/22 10:25
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResult exception(Exception e)
    {
        log.error(e.getMessage(), e);
        return ApiResult.fail("未知异常，请联系管理员！");
    }

    @ExceptionHandler(BaseException.class)
    public ApiResult baseException(BaseException e){
        return ApiResult.fail(e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ApiResult illegalArgumentException(IllegalArgumentException e)
    {
        log.error(e.getMessage(), e);
        return ApiResult.fail(e.getMessage());
    }
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<Map<String,Object>> validExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, Object> errorMap = fieldErrors.stream()
                .collect(Collectors.toMap(FieldError::getField, item -> Objects.isNull(item.getDefaultMessage())?"校验异常":item.getDefaultMessage()));
        return ApiResult.fail(errorMap,"校验异常");
    }

}
